package org.s166.userweb.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 编写过滤器，实现统一编码设置
 * 
 * @author Administrator
 *
 */

//第一：定义一个类，实现Filter接口
@WebFilter(urlPatterns = "/*",initParams = {@WebInitParam(name="encoding",value="UTF-8")})
public class EncodingFilter implements Filter{
	//第二：重写Filter接口中的方法 
	
	private String encoding ;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		String encoding = filterConfig.getInitParameter("encoding") ;
		
		this.encoding = encoding ;
		
		System.out.println("统一编码的初始化: "+encoding);
		
	}

	@Override
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
			throws IOException, ServletException {
		// 第三：实现过滤功能
		//1.向下转型
		HttpServletRequest request = (HttpServletRequest)sRequest ;
		HttpServletResponse response = (HttpServletResponse)sResponse ;
		
		//2.设置统一编码
		request.setCharacterEncoding(this.encoding); 
		//response.setContentType("text/html;charset=" + this.encoding);
		response.setCharacterEncoding(this.encoding);
		response.setContentType("application/json;charset=utf-8");


		//3.放行
		chain.doFilter(request, response);
		
	}

	@Override
	public void destroy() {
		System.out.println("统一编码过滤器－销毁");
	}
	
	
	
}













